package com.handpay.nocardpay.baselibrary.raindrops;

import android.app.Activity;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.PopupWindow;

import com.handpay.nocardpay.baselibrary.R;

/**
 * Created by sxshi on 2018-4-13.
 */

public class LoadingManager {
    private static final String TAG = "ssx-loading";
    private PopupWindow mPopupWindow;
    private Activity mContext;
    private static volatile LoadingManager instance;
    private View popView;

    private LoadingManager(Activity context) {
        mContext = context;
        popView = View.inflate(mContext, R.layout.loading, null);
    }

    public static LoadingManager getInstance(Activity activity) {
        if (instance == null) {
            synchronized (LoadingManager.class) {
                if (instance == null) {
                    instance = new LoadingManager(activity);
                }
            }
        }
        return instance;
    }

    public void showLoading() {
        dismissLoading();
        mPopupWindow = new PopupWindow(popView, 250, 250);
        mPopupWindow.setOutsideTouchable(false);
        mPopupWindow.setFocusable(false);
        setBackgroundAlpha(0.5f);
        mPopupWindow.showAtLocation(mContext.getWindow().getDecorView(), Gravity.CENTER, 0, 0);
    }

    public void dismissLoading() {
        if (null != mPopupWindow && mPopupWindow.isShowing()) {
            mPopupWindow.dismiss();
            setBackgroundAlpha(1.0f);
        }
        mPopupWindow = null;
    }

    private void setBackgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = mContext.getWindow()
                .getAttributes();
        lp.alpha = bgAlpha;
        mContext.getWindow().setAttributes(lp);
    }
}
